﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Networking;
using System.IO;
using Asset.Script.Tools;
using System;
using UnityEngine.UI;
using Random = System.Random;

namespace Asset.Script.Update
{
    [System.Serializable]
    public class ResAddress
    {
        public string res;
        public string login;
        public string androidDownUrl;//安卓安装包的下载地址
        public string iosDownUrl;//苹果商店的地址
        public int advNum;//广告数量
        public float time=2;//单张显示时间
        public float minTime=0;//最短总显示时间
        public int isOpenAdv=0;//是否开启更新广告
    }

    public delegate void CallBack(object obj);

    public class UpdateMgr : MonoBehaviour
    {
        public UILabel _msgLabel;
        private UITexture T_LoadingBar;
        public GameObject T_reconnect;

        // private string baseUpdateUrl = "http://127.0.0.1:8080/res/";
          private string baseUpdateUrl = "http://192.168.3.115:8080/res/";
        //  private string baseUpdateUrl = "http://pkres.kkpker.com:5580/res/";

        public static UpdateMgr Instance
        {
            get
            {
                if (null == _instance)
                {
                    GameObject go = new GameObject();
                    go.AddComponent<UpdateMgr>();
                    go.name = typeof(UpdateMgr).Name;
                }
                return _instance;
            }
        }
        private static UpdateMgr _instance;
        private void Awake()
        {
            if (null != _instance)
            {
                Destroy(this);
            }
            else
            {
                _instance = this;
            }

            T_reconnect.gameObject.SetActive(false);
            T_LoadingBar = GameObject.Find("T_LoadingBar").GetComponent<UITexture>();
            T_LoadingBar.gameObject.SetActive(false);
        }

        private void Start()
        {
            DoResRelease();
        }

        private void Update()
        {
            if (ReleaseStreamingAssets.Instance.ReleaseProgress >= 0)
            {
                TryShowMsg("Đang giải nén tập tin" + (int)ReleaseStreamingAssets.Instance.ReleaseProgress + "%");
                T_LoadingBar.fillAmount = ReleaseStreamingAssets.Instance.ReleaseProgress * 0.01f;
            }
            if (ReleaseStreamingAssets.Instance.DecompressionProgress >= 0)
            {
                TryShowMsg("Đang tải tập tin nén" + (int)ReleaseStreamingAssets.Instance.DecompressionProgress + "%");
                T_LoadingBar.fillAmount = ReleaseStreamingAssets.Instance.DecompressionProgress * 0.01f;
            }
        }

        private void DoResRelease()
        {
            TryShowMsg("Đang tải cấu hình");
   
         
     
                if (ReleaseStreamingAssets.Instance.IsFirstSetup)
                {
                    T_LoadingBar.gameObject.SetActive(true);
                    Debug.Log("首次安装，释放资源");
                    ReleaseStreamingAssets.Instance.ReleaseAssets(this, () =>
                    {
                        T_LoadingBar.gameObject.SetActive(false);
                        GetServerAddress(() => {
                            BeginUpdate();
                        });
                    });
                }
                else
                {
                    if(IsNeedClearOldRes())
                    {
                        ClearOldRes();
                    }
                    else
                    {
                        GetServerAddress(() => {
                            BeginUpdate();
                        });
                    }
                }
            
        }

        //覆盖安装的时候，判断是否需要先清理老资源
        private bool IsNeedClearOldRes()
        {
            string nowBigVersion = PlatformTool.Instance.GetVersion();
            Debug.Log("nowBigVersion:" + nowBigVersion);
            string[] tmp = nowBigVersion.Split(new char[] { '.' });
            int bigVersion = int.Parse(tmp[0]);

            int oldVersion = 0;
            string oldBigVersion = "";
            string oldPath = ResPathHelper.Instance.LocalFilePath() + "/Version.pig";
            if (File.Exists(oldPath))
            {
                using (StreamReader reader = File.OpenText(oldPath))
                {
                    oldBigVersion = reader.ReadToEnd();

                    Debug.Log("oldBigVersion:" + oldBigVersion);

                    string[] oldtmp = oldBigVersion.Split(new char[] { '.' });
                    Debug.Log("oldtmp[0]:" + oldtmp[0]);
                    oldVersion = int.Parse(oldtmp[0]);
                }
            }
            

            if(bigVersion > oldVersion)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        //清除老资源，并释放新资源，并检查更新
        private void ClearOldRes()
        {
            string LocalRootPath = Path.GetFullPath(ResPathHelper.Instance.LocalFilePath());
            string destPath = FilePathTool.Instance.Normalization(LocalRootPath, Application.platform);
            if(Directory.Exists(destPath))
            {
                Directory.Delete(destPath, true);
            }

            T_LoadingBar.gameObject.SetActive(true);
            Debug.Log("大版本更新，重新释放资源");
            ReleaseStreamingAssets.Instance.ReleaseAssets(this, () =>
            {
                T_LoadingBar.gameObject.SetActive(false);
                GetServerAddress(() => {
                    BeginUpdate();
                });
            });
        }


        public Texture aaa;

        private void GetServerAddress(Action callback)
        {
            if (Application.internetReachability == NetworkReachability.NotReachable)
            {
                TryShowMsg("Lỗi kết nối mạng, vui lòng kiểm tra kết nối Internet của bạn");
                T_reconnect.gameObject.SetActive(true);
                return;
            }
            List<string> urlList = new List<string>();
             urlList.Add(baseUpdateUrl+ "serverConfig.json");
       
            StartCoroutine(FixFile.Instance.DownloadConfigLua(urlList,(jsonString) =>
            {
                ResAddress obj = JsonUtility.FromJson<ResAddress>(jsonString);
                UpdateConfig.Instance.ResServerUrl = obj.res;
                UpdateConfig.Instance.LoginServerUrl = jsonString;
                UpdateConfig.Instance.androidDownUrl = obj.androidDownUrl;
                UpdateConfig.Instance.iosDownUrl = obj.iosDownUrl;
        
                Debug.Log("resServer:" + UpdateConfig.Instance.ResServerUrl);
                Debug.Log("loginServer:" + UpdateConfig.Instance.LoginServerUrl);
                Debug.Log("androidDownUrl:" + UpdateConfig.Instance.androidDownUrl);
                Debug.Log("iosDownUrl:" + UpdateConfig.Instance.iosDownUrl);
              
                
                UpdateConfig.Instance.UpdateUrl();
                serverData = obj;
                // string BirdPicturePath = "1";
                //GameObject.Find("AdvTexture").GetComponent<UITexture>().mainTexture = Resources.Load<Texture>(BirdPicturePath);
      
                callback();
            }, () =>
            {
                TryShowMsg("Lỗi kết nối. Vui lòng kiểm tra đường truyền");
                T_reconnect.gameObject.SetActive(true);
                return;
            }));
        }


        private ResAddress serverData;
        private int advNum;
        private int curAdvIndex = 1;
        private float advTime;
        private float advMinTime;
        private bool isShowComplete = false;
        private bool isUpdateComplete = false;
        private int isOpenAdv;
        public void ShowAdv(ResAddress data)
        {
            if(data.isOpenAdv==null|| data.isOpenAdv==0)
            {
                isShowComplete = true;
                return;
            }
          
            isOpenAdv = data.isOpenAdv;
            advNum = data.advNum;
            advTime = data.time;
            advMinTime = data.minTime;
            Random random = new Random();

            curAdvIndex = random.Next(1, advNum + 1);


            Invoke("ShowAdvTime", advMinTime);
            StartCoroutine(LoadImage(baseUpdateUrl + "advImage/" + (curAdvIndex%advNum+1) + ".png"));
        }

        private void ShowAdvTime()
        {
            isShowComplete = true;
            
        }

        private void NextAdvTime()
        {
            curAdvIndex++;
            if (isShowComplete&& isUpdateComplete)
            {
                EndUpdate();
            }else
            {
                StartCoroutine(LoadImage(baseUpdateUrl + "advImage/" + (curAdvIndex % advNum + 1) + ".png"));     
            }
                 
        }


        //加在广告图片
        IEnumerator LoadImage(string path)
        {

             WWW www = new WWW(path);
            //  WWW www = new WWW("file://" + path);
         
 
            yield return www;
            UITexture t = GameObject.Find("AdvTexture").GetComponent<UITexture>();
             
            if (www.isDone && www.error == null)
            {
                t.mainTexture = www.texture;
                // t.MakePixelPerfect();

                Invoke("NextAdvTime",advTime );
            }
            else
            {

                Debug.Log("Load Failuer：" + www.error);
                try
                {
                    byte[] bytes = File.ReadAllBytes(path);
                    Texture2D tex2d = new Texture2D(128, 128, TextureFormat.RGBA32, false);
                   
                }
                catch (System.Exception e)
                {
                    Debug.Log(e);
                }
            }

        }

        /// <summary>
        /// 开始更新流程
        /// </summary>
        private void BeginUpdate()
        {
            TryShowMsg("Đang tải cấu hình");
          
                ShowAdv(serverData);
                System.Action checkVersionAction = () =>
                {
                    if (Application.internetReachability == NetworkReachability.NotReachable)
                    {
                        TryShowMsg("Lỗi kết nối. Vui lòng kiểm tra đường truyền");
                        T_reconnect.gameObject.SetActive(true);
                        return;
                    }
                    CheckVersion.Instance.Check(this, (state) =>
                    {
                        if (state == CheckVersion.CheckState.Fail)
                        {
                            TryShowMsg("Lấy cấu hình thất bại,vui lòng kiểm tra kết nối Internet của bạn");
                            T_reconnect.gameObject.SetActive(true);
                        }
                        else if (state == CheckVersion.CheckState.NoUpdate)
                        {
                            Debug.Log("无需更新,当前版本：" + CheckVersion.Instance.LocalVersion());
                            isUpdateComplete = true;
                            if (isShowComplete)
                            {
                                EndUpdate();
                            }
                        }
                        else if (state == CheckVersion.CheckState.NeedUpdate)
                        {
                            T_LoadingBar.gameObject.SetActive(true);
                            
                            //开始更新
                            StartCoroutine(CheckVersion.Instance.GetMD5List(UpdateConfig.Instance.MD5Url, (md5list) =>
                             {
                                 FixFile.State Fixstate = FixFile.Instance.Fix(UpdateConfig.Instance.ResServerRoot, md5list);
                                 if (Fixstate == FixFile.State.NeedFix)
                                 {
                                     FixFile.Instance.Download.m_OnAllSuccess += (a, b) =>
                                     {
                                         Debug.Log("更新配置完成,当前版本：" + CheckVersion.Instance.LocalVersion());
                                         isUpdateComplete = true;
                                         if (isShowComplete)
                                         {
                                             EndUpdate();
                                         }
                                        
                                     };
                                     FixFile.Instance.Download.m_OnFailed += (a, b) =>
                                     {
                                         Debug.Log("更新文件出现异常");
                                         TryShowMsg("Cập nhật tài nguyên lỗi, vui lòng kiểm tra kết nối Internet của bạn");
                                         T_reconnect.gameObject.SetActive(true);
                                     };
                                     FixFile.Instance.Download.m_OnSuccess += (a, b) =>
                                     {
                                         float progress = (float)FixFile.Instance.Download.CurProgress / (float)FixFile.Instance.Download.Total;
                                         progress = progress * 100f;
                                         TryShowMsg("Đang cập nhật tài nguyên" + (int)progress + "%");
                                         T_LoadingBar.fillAmount = progress * 0.01f;
                                     };
                                 }
                                 else if (Fixstate == FixFile.State.NotNeed)
                                 {
                                     Debug.LogError("没有文件改变");
                                     isUpdateComplete = true;
                                     if(isShowComplete)
                                     {
                                         EndUpdate();
                                     }
                                     
                                 }
                                 else if (Fixstate == FixFile.State.Fixing)
                                 {
                                     Debug.Log("正在修复中");
                                 }
                             }));
                        }
                        else if (state == CheckVersion.CheckState.NeedResetup)
                        {
                            string url = null;
                            if(Application.platform == RuntimePlatform.Android)
                            {
                                url = UpdateConfig.Instance.androidDownUrl;
                            }
                            else if (Application.platform == RuntimePlatform.IPhonePlayer)
                            {
                                url = UpdateConfig.Instance.iosDownUrl;
                            }
                            else
                            {
                                url = "";
                            }
                            TryShowMsg("[url="+ url + "][u]Phiên bản đang hết hạn, nhấp để cập nhật phiên bản mới nhất[/u][/url]");
                        }
                    });
                };
                checkVersionAction();
            
        }


        private void EndUpdate()
        {
            T_LoadingBar.gameObject.SetActive(false);
            GameObject go = new GameObject();
            go.AddComponent<Initialization>();
            TryShowMsg("Vào trò chơi");
            float end = System.Environment.TickCount;
        }
        private void Reset()
        {
            this.gameObject.name = this.GetType().Name;
        }
        private void TryShowMsg(string str)
        {
            if (null == _msgLabel)
            {
                _msgLabel = GameObject.FindObjectOfType<UILabel>();
            }
            if (null != _msgLabel)
                _msgLabel.text = str;
        }

        //重新执行一遍更新流程
        public void Reconnect()
        {
            T_reconnect.gameObject.SetActive(false);
            DoResRelease();
        }

        public void Quit()
        {
            Application.Quit();
        }
    }
}


